package cn.com.dstz.admin.action;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;

import cn.com.dstz.agent.config.VideoConfig;
import cn.com.dstz.base.action.BaseAction;
import cn.com.dstz.utils.ActionUtils;
import cn.com.dstz.utils.DataBaseUtils;
import cn.com.dstz.utils.DateUtils;
import cn.com.dstz.utils.ValidUtils;
import cn.com.dstz.web.constants.Constants;

public class VideoAct extends BaseAction{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public void list(){
		Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
		int level = ActionUtils.getAdminLevel( admin );
		
		String sql = "select v.*, a.username from dstz_video v, dstzadmin a where v.adminid = a.id";
		Map< String, Object > valueMap = null;
		
		if( level > 0 ){
			VideoConfig config = new VideoConfig( admin, this.countManagerGroup( ) );
			sql += config.getSQL( );
			valueMap = config.getValueMap( );
		}
	
		this.responseToJsonObject( this.paginationBySQL( sql, null, valueMap,"v.sendtime" )  );
		return;
	}
	
	public void add(){
		int validSaveOrUpdate = this.validSaveOrUpdate( 0 );
		
		if( validSaveOrUpdate > 0 ){
			this.ajaxResponse( validSaveOrUpdate );
			return;
		}
		if(ValidUtils.validLength( imagePath, 1, 2000 )){
			this.ajaxResponse( 4 );
			return ;
		}
		Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
		
		int save = baseService.save( "dstz_video", DataBaseUtils.getData( new String[]{
				"title","adminid", "aid",  "path","imagePath","sendtime"
		}, new Object[]{
				title,admin.get( "id" ),admin.get( "topaid" ),  path, imagePath,DateUtils.getCurrentTime( )
		} ) );
		
		this.addLog( save, "video", 0,  path );
		this.ajaxResponse( save > 0 ? 0 : -1 );
		return;
	}
	
	public void edit(){
		int validSaveOrUpdate = this.validSaveOrUpdate(1);
		if(validSaveOrUpdate>0){
			this.ajaxResponse(validSaveOrUpdate);
			return ;
		}
		Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
		Map< String, Object > whereData = new HashMap< String, Object >( );
		int level = ActionUtils.getAdminLevel( admin );
		whereData.put( "id", id );
		
		if( level > 0 ){
			whereData.put( "aid", admin.get( "topaid" ) );
		}
		Map<String,Object> valueMap=DataBaseUtils.getData(new String[]{
				"title","adminid", "aid",  "path","sendtime"
		}, new Object[]{
				title,admin.get( "id" ),admin.get( "topaid" ),  path, DateUtils.getCurrentTime( )
		});
		if(StringUtils.isNotBlank(imagePath)){
			valueMap.put("imagePath", imagePath);
		}
		int update  = baseService.update("dstz_video",valueMap , whereData);
		this.addLog(update, "video", 0, title);
		this.ajaxResponse(update>0?0:-1);
		return;
	}
	
	public String toView(){
		String sql = "select v.* from dstz_video v where v.id = :id";
		Map< String, Object > valueMap = new HashMap< String, Object >( );
		valueMap.put( "id", id );
		Map< String, Object > data = baseService.queryForMap( sql, valueMap );
		getRequest( ).setAttribute( "data", data );
		return "toview";
	}
	public String toedit( ){
		
		int validSaveOrUpdate = validSaveOrUpdate( 2 );
		
		if( validSaveOrUpdate > 0 ){
			this.alertMsg( null );
			return "edit";
		}
		String sql = "select v.*, a.username from dstz_video v, dstzadmin a where v.adminid = a.id and v.id=:id";
		Map< String, Object > valueMap = new HashMap< String, Object >( );
		valueMap.put( "id", id );
		Map< String, Object > data = baseService.queryForMap( sql, valueMap );
		getRequest( ).setAttribute( "data", data );
		return "edit";
		
	}
	
	public void listVideo(){
		String aid = getRequest().getParameter("aid");
		if(StringUtils.isEmpty(aid)){
			return ;
		}
		String sql = "select v.* from dstz_video v where v.aid = :aid order by v.sendtime desc";
		Map< String, Object > valueMap = new HashMap<String,Object>();
		valueMap.put("aid", aid);
		Map<String,Object> resultMap = this.paginationBySQL( sql, null, valueMap,"" );
		List< Map< String, Object >> resultList = ( List< Map< String, Object >>) resultMap.get( "rows" );
		for( Map< String, Object > result : resultList ){
			String content = ( String ) result.get( "title" );
			content = Jsoup.clean( content, Whitelist.none( ) );
			int len = content.length( );
			
			if( len > 21 ){
				content = content.substring( 0, 20 ) + ".....";
			}
			result.put( "title", content );
		}
		this.responseToJsonObject(   resultMap);
		return;
	}
	
	public void delete( ){
		
		String ids = getParameter( "ids" );
		
		if( ids != null ){
			String [] splitIds = StringUtils.split( ids, "," );
			
			if( splitIds != null && splitIds.length > 0 ){
				List< String > updateSqlList = new ArrayList< String >( );
				
				Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
				int level = ActionUtils.getAdminLevel( admin );
				
				for( String id : splitIds ){
					if( StringUtils.isNotBlank( id )){
						String delSql = "delete from dstz_video where id=" + id;
						if( level > 0 ){
							delSql += " and adminid=" + admin.get( "id" );
						}
						
						updateSqlList.add(  delSql );
					}
				}
				int del = baseService.saveOrUpdateBatch( updateSqlList );
				
				this.addLog( del, "video", 2, ids );
			}
		}
	}
	
	public String toadd(){
		return "add";
	}
	public void fileupload(){
		String realpath = ServletActionContext.getServletContext().getRealPath("/");
		String filepath = "/hd_v2/video/images/";
		String savename=UUID.randomUUID()+Filename.substring(Filename.lastIndexOf("."));
		if(StringUtils.isBlank(Filename)){
			this.ajaxResponse(4);
			return ;
		}
		String imagesPath = realpath+filepath+savename;
		File uploadFile = new File( imagesPath);
		try {
			org.apache.commons.io.FileUtils.copyFile(Filedata, uploadFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.ajaxResponse(filepath+savename);
		return ;
	}
	private int validSaveOrUpdate( int saveOrUpdate ){
		if( saveOrUpdate == 2 || saveOrUpdate == 1 ){
			if( id == null || id == 0 ){
				return 3;
			}
			if( saveOrUpdate == 2 ){
				return 0;
			}
		}
		if( ValidUtils.validLength( path, 1, 2000 )){
			return 1;
		}
		
		return 0;
		
	}
	
	private Integer id;
	private String path;
	private String title;
	private File Filedata;
	private String Filename;
	private String imagePath;
	
	public String getImagePath() {
		return imagePath;
	}

	public void setImagePath(String imagePath) {
		if(StringUtils.isNotBlank(imagePath)){
			imagePath=decode(imagePath);
		}
		this.imagePath = imagePath;
	}

	public File getFiledata() {
		return Filedata;
	}

	public void setFiledata(File filedata) {
		Filedata = filedata;
	}

	public String getFilename() {
		return Filename;
	}

	public void setFilename(String filename) {
		if(StringUtils.isNotBlank(filename)){
			filename = decode(filename);
		}
		Filename = filename;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		if(StringUtils.isNotBlank(title)){
			title = decode(title);
		}
		this.title = title;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		if(StringUtils.isNotBlank(path)){
			path = decode(path);
		}
		this.path = path;
	}


}
